package cn.nawang.ebeim.ui.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @ClassName: CommandUtil
 * @Description: TODO
 * @author fanyb
 * @date Nov 17, 2015 2:28:50 PM
 * @version v1.0
 */
public class CommandUtil {
  public static String CMD_START_SERVICES_EBEIMSERVICE= "cmd /c net start ebeimService";
  public static String CMD_STOP_SERVICE_EBEIMSERVICE = "cmd /c net stop ebeimService";
  public static String CMD_STRAT_SERVICE_EBEIMPROJECT = "cmd /c net start EbeimProtect";
  public static String CMD_STOP_SERVICE_EBEIMPROJECT = "cmd /c net stop EbeimProtect";
  
  public static String CMD_NET_START="cmd /c net start";
  
  /**
   * 
   * @author fanyb
   * @Description: 执行cmd命令（windows）
   * @param command windows命令
   * @throws IOException 
   * @date Nov 17, 20153:57:42 PM
   *
   * @修改人 
   * @修改日期
   */
  public static void executeCommand(String command) throws IOException {
    Runtime runtime = Runtime.getRuntime();
    Process process;
    process = runtime.exec(command);
    BufferedReader br =
        new BufferedReader(new InputStreamReader(process.getInputStream(), "gb2312"));
    String inline;
    while ((inline = br.readLine()) != null) {
      System.out.println(inline);
    }
    br.close();
  }
 
  /**
   * 
   * @author fanyb
   * @Description: 判断某个服务是否启动（windows）
   * @param command CMD_NET_START（罗列服务启动项）
   * @param service 服务名称
   * @return boolean 
   * @throws IOException
   * @date Nov 17, 20153:56:28 PM
   *
   * @修改人 
   * @修改日期
   */
  public static boolean isStartService(String command,String service)throws IOException{
    Runtime runtime = Runtime.getRuntime();
    Process process;
    process = runtime.exec(command);
    BufferedReader br =
        new BufferedReader(new InputStreamReader(process.getInputStream(), "gb2312"));
    String inline;
    while ((inline = br.readLine()) != null) {
      if(service.equals(inline.trim())){
        System.out.println("该服务已经启动");
        br.close();
        return true;
      }
    }
    br.close();
    System.out.println("该服务没有启动");
    return false;
  }

  public static void main(String[] args) {    
    try {
//      CommandUtil.executeCommand(CMD_START_SERVICES_EBEIMSERVICE);
      //CommandUtil.executeCommand(CMD_STOP_SERVICES_EBEIMSERVICE);
      CommandUtil.executeCommand(CMD_NET_START);
      CommandUtil.isStartService(CMD_NET_START,"ebeimService");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
